package cn.yuanqiao.archive.detection.service.impl;

import cn.yuanqiao.archive.appManager.domain.DataScopeBase;
import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantCodeRule;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.mapper.TenantCateMdataListMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.service.ITenantCodelistService;
import cn.yuanqiao.archive.appManager.service.ITenantCoderuleService;
import cn.yuanqiao.archive.detection.domain.Detection;
import cn.yuanqiao.archive.detection.domain.DetectionScheme;
import cn.yuanqiao.archive.detection.mapper.DetectionSchemeMapper;
import cn.yuanqiao.archive.detection.service.IDetectionSchemeService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.yuanqiao.common.utils.PageUtils.startPage;

/**
 * 四性检测方案Service业务层处理
 * 
 * @author xy
 * @date 2023-08-07
 */
@Service
public class DetectionSchemeServiceImpl implements IDetectionSchemeService 
{
    @Autowired
    private DetectionSchemeMapper detectionSchemeMapper;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    @Autowired
    private TenantCateMdataListMapper tenantCateMdataListMapper;
    @Autowired
    private ITenantCoderuleService tenantCoderuleService;

    @Autowired
    private ITenantCodelistService tenantCodelistService;

    /**
     * 查询四性检测方案
     * 
     * @param id 四性检测方案主键
     * @return 四性检测方案
     */
    @Override
    public DetectionScheme selectDetectionSchemeById(Long id)
    {
        return detectionSchemeMapper.selectDetectionSchemeById(id,new DetectionScheme().getTableName());
    }

    /**
     * 查询四性检测方案列表
     * 
     * @param detectionScheme 四性检测方案
     * @return 四性检测方案
     */
    @Override
    public List<DetectionScheme> selectDetectionSchemeList(DetectionScheme detectionScheme)
    {
        return detectionSchemeMapper.selectDetectionSchemeList(detectionScheme,SecurityUtils.getTenantCode());
    }

    /**
     * 新增四性检测方案
     * 
     * @param detectionScheme 四性检测方案
     * @return 结果
     */
    @Override
    public int insertDetectionScheme(DetectionScheme detectionScheme)
    {
        //验证标识以及门类Id
        int count=detectionSchemeMapper.getCountByIdentification(detectionScheme.getIdentification(),detectionScheme.getTableName());
        if(count>0){
            throw new ServiceException("标识不能重复！");
        }
        detectionScheme.setState(0);
        detectionScheme.setIsDel(0);
        detectionScheme.setCreateId(SecurityUtils.getUserId());
        detectionScheme.setCreateTime(DateUtils.getNowDate());
        //获取门类的subTaleName
        TenantCategory tenantCategory= tenantCategoryMapper.selectTenantCategoryByID(detectionScheme.getCategoryId(),new TenantCategory().getTableName());
        String type=detectionScheme.getType();
        if("0".equals(type)){
            //组件
          detectionScheme.setSubTableName(tenantCategory.getFileTableName());
        }else if("1".equals(type)){
            //组卷
          detectionScheme.setSubTableName(tenantCategory.getFolderTableName());
        }else if("3".equals(type)){
            //项目
            detectionScheme.setSubTableName(tenantCategory.getItemTableName());
        }



        return detectionSchemeMapper.insertDetectionScheme(detectionScheme);
    }

    /**
     * 修改四性检测方案
     * 
     * @param detectionScheme 四性检测方案
     * @return 结果
     */
    @Override
    public int updateDetectionScheme(DetectionScheme detectionScheme)
    {
        //验证标识以及门类Id
        int count=detectionSchemeMapper.getCountByIdentification(detectionScheme.getIdentification(),detectionScheme.getTableName());
        DetectionScheme scheme=detectionSchemeMapper.selectDetectionSchemeById(detectionScheme.getId(),detectionScheme.getTableName());
        if(!scheme.getIdentification().equals(detectionScheme.getIdentification())){
            if(count>0){
                throw new ServiceException("标识不能重复！");
            }
        }

        detectionScheme.setLastupdateTime(DateUtils.getNowDate());
        detectionScheme.setLastupdateId(SecurityUtils.getUserId());
        TenantCategory tenantCategory= tenantCategoryMapper.selectTenantCategoryByID(detectionScheme.getCategoryId(),new TenantCategory().getTableName());
        String type=detectionScheme.getType();
        if("0".equals(type)){
            //组件
            detectionScheme.setSubTableName(tenantCategory.getFileTableName());
        }else if("1".equals(type)){
            //组卷
            detectionScheme.setSubTableName(tenantCategory.getFolderTableName());
        }else if("3".equals(type)){
            //项目
            detectionScheme.setSubTableName(tenantCategory.getItemTableName());
        }
        return detectionSchemeMapper.updateDetectionScheme(detectionScheme);
    }

    /**
     * 批量删除四性检测方案
     * 
     * @param ids 需要删除的四性检测方案主键
     * @return 结果
     */
    @Override
    public int deleteDetectionSchemeByIds(Long[] ids)
    {
        return detectionSchemeMapper.deleteDetectionSchemeByIds(ids,new DetectionScheme().getTableName());
    }

    /**
     * 删除四性检测方案信息
     * 
     * @param id 四性检测方案主键
     * @return 结果
     */
    @Override
    public int deleteDetectionSchemeById(Long id)
    {
        return detectionSchemeMapper.deleteDetectionSchemeById(id);
    }

    @Override
    public List<TenantMdataList> getSchemelist(TenantMdataList yqdaMdataList) {
        Long categoryId = yqdaMdataList.getCategoryId();
        TenantCategory tenantCategory = new TenantCategory();
        String groupId = tenantCategoryMapper.selectGroupIdById(categoryId, tenantCategory.getTableName());
        if(!StringUtils.isNotEmpty(groupId)){
            throw new ServiceException("请元数据方案");
        }
        yqdaMdataList.setGroupId(Long.valueOf(groupId));
        List<TenantMdataList> tenantMdataLists = tenantCateMdataListMapper.getSchemelist(yqdaMdataList);
        return tenantMdataLists;
    }

    @Override
    public List<Detection> selectTreeList(String code) {
        //0 归档 1:移交 2:长期
        List<Detection> detectionsList=detectionSchemeMapper.selectDetectionList(code);
        return createTree(0L,detectionsList);
    }

    @Override
    public List getDhList(Long categoryId, String type) {
        //获取档号
        Map map=new HashMap<>();
        List list1=new ArrayList();
        TenantCodeRule yqdaCoderuleModel=new TenantCodeRule();
        yqdaCoderuleModel.setCategoryModelId(categoryId);
        List<TenantCodeRule> list = tenantCoderuleService.selectYqdaCoderuleModelList(yqdaCoderuleModel);
        for(TenantCodeRule tenantCodeRule:list){
            JSONObject jsonObject=tenantCodelistService.getdetail(type,tenantCodeRule.getId());
            if(type.equals("v")){
                List ziduanarr= (List) jsonObject.get("ziduanarr");
                List fuhaoarr= (List) jsonObject.get("fuhaoarr");
                String jianlianjie=jsonObject.getString("jianlianjie");
                String jianziduan=jsonObject.getString("jianziduan");

                String juandh="";
                String jiandh="";

                for(int i=0;i<ziduanarr.size();i++){
                    TenantMdataList tenantMdataList=new TenantMdataList();
                    tenantMdataList.setCategoryId(categoryId);
                    tenantMdataList.setType(1);
                    tenantMdataList.setFieldName(ziduanarr.get(i).toString());
                    List<TenantMdataList> tenantMdataLists=getSchemelist(tenantMdataList);
                    if(i==(ziduanarr.size()-1)){
                        juandh+=tenantMdataLists.get(0).getFieldCaption();
                        //件
                        if(!"".equals(jianlianjie)){
                            jiandh+=juandh+jianlianjie;
                        }
                        if(!"".equals(jianziduan)){
                            TenantMdataList jiantenantMdataList=new TenantMdataList();
                            jiantenantMdataList.setCategoryId(categoryId);
                            jiantenantMdataList.setType(0);
                            jiantenantMdataList.setFieldName(jianziduan);
                            List<TenantMdataList> jiantenantMdataLists=getSchemelist(jiantenantMdataList);
                            jiandh+=jiantenantMdataLists.get(0).getFieldCaption();
                        }
                    }else{
                        juandh+=tenantMdataLists.get(0).getFieldCaption()+fuhaoarr.get(i).toString();

                    }
                }

                     map.put("jiandh",jiandh);
                     map.put("juandh",juandh);
                     list1.add(map);
            }else if("f".equals(type)){
                List ziduanarr= (List) jsonObject.get("ziduanarr");
                List fuhaoarr= (List) jsonObject.get("fuhaoarr");


                String juandh="";
                String jiandh="";

                for(int i=0;i<ziduanarr.size();i++){
                    TenantMdataList tenantMdataList=new TenantMdataList();
                    tenantMdataList.setCategoryId(categoryId);
                    tenantMdataList.setType(0);
                    tenantMdataList.setFieldName(ziduanarr.get(i).toString());
                    List<TenantMdataList> tenantMdataLists=getSchemelist(tenantMdataList);
                    if(i==(ziduanarr.size()-1)){
                        jiandh+=tenantMdataLists.get(0).getFieldCaption();
                    }else{
                        jiandh+=tenantMdataLists.get(0).getFieldCaption()+fuhaoarr.get(i).toString();

                    }
                }

                map.put("jiandh",jiandh);
                map.put("juandh",juandh);
                list1.add(map);
            }
        }

        return list1;
    }

    @Override
    public List<Detection> objectTree(Long id, String code) {
        //获取树

        return detectionSchemeMapper.objectTree(id,code);
    }

    @Override
    public List<DetectionScheme> selectDetectionSchemeListByRole(DetectionScheme detectionScheme) {
        return detectionSchemeMapper.selectDetectionSchemeListByRole(new DataScopeBase(),detectionScheme,SecurityUtils.getTenantCode());

    }

    @Override
    public List<TenantMdataList> getNewSchemelist(TenantMdataList yqdaMdataList) {
        Long categoryId = yqdaMdataList.getCategoryId();
        TenantCategory tenantCategory = new TenantCategory();
        String groupId = tenantCategoryMapper.selectGroupIdById(categoryId, tenantCategory.getTableName());
        if(!StringUtils.isNotEmpty(groupId)){
            throw new ServiceException("请元数据方案");
        }
        yqdaMdataList.setGroupId(Long.valueOf(groupId));
        startPage();
        List<TenantMdataList> tenantMdataLists = tenantCateMdataListMapper.getSchemelist(yqdaMdataList);
        return tenantMdataLists;

    }

    private List<Detection> createTree(Long pid, List<Detection> detections) {
        List<Detection> treeList = new ArrayList<>();
        for (Detection detection : detections) {
            if(pid.equals(0)){
                if(detection.getSuperId().equals(0)){    //那这就是第一级节点
                    detection.setIsDetection("1");
                    detection.setIsPass("0");
                    treeList.add(detection);
                    detection.setChildren(createTree(detection.getId(), detections));
                }
            }else{
                if (pid.equals(detection.getSuperId())) {
                    detection.setIsDetection("1");
                    detection.setIsPass("0");
                    treeList.add(detection);
                    detection.setChildren(createTree(detection.getId(), detections));
                }
            }
//            当children为[]的时候，将他设置成null
           if(detection.getChildren()==null||detection.getChildren().size()==0){
               detection.setChildren(null);
            }
        }
        return treeList;
    }



}
